/**
  ******************************************************************************
  * 项目名：tcp转接板-ttl-485-can-jd-out
  * 开发者：CAI
  ******************************************************************************
  *
  ******************************************************************************
 **/
/*------------------------------------------------------------------------------
-------------------------------------------------------------------------------*/

#include "stm32f10x.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "defined.h"
#include "uart_tcp.h"
#include "timer.h"
#include "rtc.h"
#include "adam.h"
#include "ec20.h"
#include "protocol.h"
#include "emqmqtt.h"
#include "stmflash.h"
/*-----------------------------------------------------------------------------*/
u32 sysTimebase_ms ;
/*----------------------uart2tcp-----------------------------------------------------*/
MT_POST_STR   	Post_Info,Post_InfoBAK;//上传信息,及备份
u16	uart_over_timecnt;
u8 IR_postflag,MT_postflag,QR_postflag,Alarm_postflag,DL_postflag,CtlErrflag,ScanErrflag,CtlOKflag,ScanOKflag;
u8 CMDnode,SCANnode,LastCMD;//操控指令标识，浏览指令标识
u8 testflag,testk;
u8 rxtest[20];
u16  tx_Read_timebase;//循环读计时
SOCKET_AT_TYPE  Tx_Ready_Node;
SOCKET_AT_TYPE  Bak_Ready_Node[10];//指令包
TCP_Rx_STR  TcpStr[6];//接收数据

extern ModbusRTUData Regdata;
//-------------------------------------------------------------------
//uchar DeviceSN[10];	
//BYTE PassWord[10];
//计时相关
#define counter_base 5
typedef struct
{
    uchar tm_sec;
    uchar tm_min;
    uchar tm_hour;
    uchar tm_day;
    uchar tm_mon;
    uchar tm_week;
    uint tm_year;
} CurrentDateTimes;

static CurrentDateTimes  device_time;
static uchar counter_1ms =0;//1ms
static uchar Timebase_delay_5ms = 0;
static u16 Timebase_ms = 0;

uchar counter_10ms = 0;				//2 -- 5ms
uchar counter_100ms = 0;			//20 -- 5ms
uchar counter_250ms = 0;			//50 -- 5ms
uchar counter_500ms = 0;			//100 -- 5ms
uchar counter_1s = 0;					//200 -- 5ms
u16 counter_3s = 0;

//月的天数
const uchar MaxDayArray[12]= {31,28,31,30,31,30,31,31,30,31,30,31};
static u16 CPU_Usage_begin, CPU_Usage_end;		//记录CPU使用率计算（5ms内占用多少ms）
u16 CPU_Usage_value = 0, Ret_CPU_Usage = 0;		//记录CPU使用情况（1s内占用多少ms）

//作为主动端时的变量
#define Unsynsend			0
#define TcpSendLdle 	3		//空闲
#define TcpSendBusy		4		//发送中
#define TcpBackErr 		5		//错误回馈

TypeEquipmentUDPHandle  EquProlVar;
u16 EquRevLen;	//接收到的数据包长度

u8 PCtcp_RevBuf[128];			//接收缓存(解密后)
u8 PCtcp_SendBuf[128];			//发送缓存(加密前)
u8 TCP_Connect_State, TCP_Connect_Time;
u8 PackageNUM;
u16 PCtcp_SendBuf_len;
/* ********************************************************************** */

/* ********************************************************************** */

/* ********************************************************************** */

void delay_us(uint time)		//72M--->1/72us
{
    unsigned int i,j;

    for(i=0; i<time; i++)
    {   //1us
        j = 6;
        while((--j)!=0);
    }
}

void delay_ms(uint ms)
{
    unsigned int i,j;

    //由于喂狗，最大不可超过5s
    if(ms > 5000)
        ms = 5000;
    for(i=0; i<ms; i++)
    {   //1ms
        j = 30000;
        while((--j)!=0);
    }
}


void Time_Set(void);
void Handler_err_function(void);
void Get_Ddfault_MAC(void);
void TransmitPacket(void);
void ReturnPCAsk(u16 leng);

////////////////////////////////////////////////////////////////////
#include "myformat.c"
//#include "drives/pc_ajr.c"
#include "drives/pc_485.c"
//#include "drives/udp.c"

////////////////////////////////////////////////////////////////////
/**
  * @brief  Configures the different GPIO ports.
  * @param  None
  * @retval None
  */
void GPIO_Configuration(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;

    //时钟
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA |RCC_APB2Periph_GPIOB | RCC_APB2Periph_GPIOC |
                           RCC_APB2Periph_GPIOD | RCC_APB2Periph_GPIOE | RCC_APB2Periph_AFIO, ENABLE);
    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA2, ENABLE);

    /* Configure PA2 as alternate function push-pull */
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    /* Configure PC1, PC2 and PC3 as alternate function push-pull */
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_Init(GPIOC, &GPIO_InitStructure);

    /* Configure PB5, PB8, PB11, PB12 and PB13 as alternate function push-pull */
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_11 | GPIO_Pin_12 | GPIO_Pin_13;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_Init(GPIOB, &GPIO_InitStructure);

    /**************************************************************/
    /*               For Remapped Ethernet pins                   */
    /*************************************************************/
    /* Input (Reset Value):
    - ETH_MII_CRS CRS: PA0
    - ETH_MII_RX_CLK / ETH_RMII_REF_CLK: PA1
    - ETH_MII_COL: PA3
    - ETH_MII_RX_DV / ETH_RMII_CRS_DV: PD8
    - ETH_MII_TX_CLK: PC3
    - ETH_MII_RXD0 / ETH_RMII_RXD0: PD9
    - ETH_MII_RXD1 / ETH_RMII_RXD1: PD10
    - ETH_MII_RXD2: PD11
    - ETH_MII_RXD3: PD12
    - ETH_MII_RX_ER: PB10 */

    /* Configure PA0, PA1 and PA3 as input */
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    /* Configure PB10 as input */
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOB, &GPIO_InitStructure);

    /* Configure PD8, PD9, PD10, PD11 and PD12 as input */
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_10;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOD, &GPIO_InitStructure);

    /**************************************************************/
    /**************************************************************/
    /////////////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////
    //输出
    //f_cs--PC4、f_wp--PA4、OC1--PE7
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_4;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_Init(GPIOC, &GPIO_InitStructure);
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_Init(GPIOE, &GPIO_InitStructure);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_Init(GPIOB, &GPIO_InitStructure);
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_Init(GPIOC, &GPIO_InitStructure);
    GPIO_SetBits(GPIOB, GPIO_Pin_14);
    //SPI片选不选择
    GPIO_SetBits(GPIOA, GPIO_Pin_4);									//Flash
    GPIO_ResetBits(GPIOC, GPIO_Pin_4);
    ////////////////////////////////////////////////////////////////////////////
    //USART1  --- 485
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);	//时钟
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;								//Tx
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;							//Rx
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;							//Rx
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
    //USART2  --- ttl
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);	//时钟
    GPIO_PinRemapConfig(GPIO_Remap_USART2, ENABLE);					//映射USART2
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;								//Tx
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOD, &GPIO_InitStructure);
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;								//Rx
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOD, &GPIO_InitStructure);
    //SPI1
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);		//时钟
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_Init(GPIOA, &GPIO_InitStructure);


    //USART3  ---
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);	//时钟
    GPIO_PinRemapConfig(GPIO_PartialRemap_USART3,ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC|RCC_APB2Periph_AFIO,ENABLE);
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;								//Tx
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOC, &GPIO_InitStructure);
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;								//Rx
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOC, &GPIO_InitStructure);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15;								//Tx
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
    GPIO_SetBits(GPIOA, GPIO_Pin_15);

    //USART5  ---
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_UART5, ENABLE);	//时钟

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;								//Tx
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOC, &GPIO_InitStructure);
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;								//Rx
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOD, &GPIO_InitStructure);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;			//TxEn
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_Init(GPIOD, &GPIO_InitStructure);
    GPIO_ResetBits(GPIOD, GPIO_Pin_1);

    /* Configure PA0, PA1 and PA3 as input */
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7|GPIO_Pin_8|GPIO_Pin_9|GPIO_Pin_10|GPIO_Pin_11|
                                  GPIO_Pin_12|GPIO_Pin_13|GPIO_Pin_14|GPIO_Pin_15;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOE, &GPIO_InitStructure);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11|GPIO_Pin_12;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOD, &GPIO_InitStructure);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOB, &GPIO_InitStructure);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3|GPIO_Pin_4|GPIO_Pin_5|GPIO_Pin_6;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_Init(GPIOE, &GPIO_InitStructure);

    //GPIOC13初始化设置    PWR脚
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;//普通输出模式
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;//50MHz
    GPIO_Init(GPIOC, &GPIO_InitStructure);//初始化

    GPIO_ResetBits(GPIOC, GPIO_Pin_13);
    delay_ms(100);
    GPIO_SetBits(GPIOC, GPIO_Pin_13);
    delay_ms(1000);
    GPIO_ResetBits(GPIOC, GPIO_Pin_13);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
void NVIC_Configuration(void)
{
    /* Set the Vector Table base location at 0x08000000 */
    NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x08002000);
}
// ===========================================================================================网络初始化
// =========================================================================================== 嘀嗒
void TB_Init(void)
{
    SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8);
    SysTick_Config(SystemFrequency / 1000);	//启用SysTick中断，在1msec
}

void SysTickTask(void)
{
    Timebase_ms++;	//uip时钟
    sysTimebase_ms++;

    if(counter_1ms)
        counter_1ms--;
    if(Timebase_delay_5ms)	//任务时钟
        Timebase_delay_5ms--;
}
////自身ms
//void Get_systime1ms(u32 time, char* asc)
//{
//	sprintf(asc,"%d",time);
//}
// ===========================================================================================uIP
//用于uip的时间：单位ms
clock_time_t clock_time(void)
{
    return Timebase_ms;
}

// =========================================================================================== RTC
//将秒转化成具体的时间：365*24*60*60 = 365*86400 = 31536000(0x01E13380)
//u32可以达到136年，一般以2000年元旦为起点（星期六）。
void Time_Regulate(void)
{
    u32 TimeVar;
    u16 temp, i;

    //读取RTC
    TimeVar = RTC_GetCounter();
    //年月日星期，需要计算
    device_time.tm_year = 2000;
    device_time.tm_mon = 1;
    device_time.tm_day = 1;
    device_time.tm_week = 6;
    if(TimeVar > 86400)
    {
        while(TimeVar > 86400)
        {
            device_time.tm_day++;
            if(
                ( ((device_time.tm_year%400)==0) || (((device_time.tm_year%4)==0)&&((device_time.tm_year%100)!=0)) )
                && (device_time.tm_mon == 2) )
            {   //是闰月
                if(device_time.tm_day > (MaxDayArray[device_time.tm_mon-1]+1))
                {
                    device_time.tm_day = 1;
                    device_time.tm_mon++;
                }
            }
            else
            {   //不是闰月
                if(device_time.tm_day > MaxDayArray[device_time.tm_mon-1])
                {
                    device_time.tm_day = 1;
                    device_time.tm_mon++;
                    if(device_time.tm_mon > 12)
                    {
                        device_time.tm_mon = 1;
                        device_time.tm_year++;
                        if(device_time.tm_year > 2099)
                        {
                            device_time.tm_year = 2000;
                        }
                    }
                }
            }
            TimeVar -= 86400;
        }
        //自动计算星期.
        temp = device_time.tm_year - 2000 + 6; //每年365天，52个星期余1天，即每年星期数加1；
        for(i=2000; i<device_time.tm_year; i++) //瑞年，天数多1，即星期数再加1
        {
            if( ((i%400)==0)||(((i%4)==0)&&((i%100)!=0)) )
                temp++;
        }
        //本年已经过去的月，根据每月的天数，
        for(i=0; i<device_time.tm_mon-1; i++)
            temp += MaxDayArray[i];
        //如果本年是瑞年,而且已经过了2月份.
        if(
            ( ((device_time.tm_year%400)==0) || (((device_time.tm_year%4)==0)&&((device_time.tm_year%100)!=0)) )
            && (device_time.tm_mon > 2) )
        {
            temp++;
        }
        //本月已过的天数
        temp += (device_time.tm_day-1);
        //总和除以7，余数就是当天的星期。（0 =星期日）
        temp = temp%7;
        device_time.tm_week = (uchar)temp;
    }
    //时分秒，可以直接得到
    device_time.tm_hour = (TimeVar % 86400)/3600;
    device_time.tm_min = (TimeVar % 3600)/60;
    device_time.tm_sec = (TimeVar % 3600)% 60;
}

//时间的刷新：在现有基础上
void Time_Increase(void)
{
    u16 i, temp;

    device_time.tm_sec++;
    if(device_time.tm_sec > 59)
    {
        device_time.tm_sec -= 60;		//减少累计误差
        device_time.tm_min++;
        if(device_time.tm_min > 59)
        {
            device_time.tm_min = 0;
            device_time.tm_hour++;
            if(device_time.tm_hour > 23)
            {
                device_time.tm_hour = 0;
                device_time.tm_day++;
                if(
                    ( ((device_time.tm_year%400)==0) || (((device_time.tm_year%4)==0)&&((device_time.tm_year%100)!=0)) )
                    && (device_time.tm_mon == 2) )
                {   //是闰月
                    if(device_time.tm_day > (MaxDayArray[1]+1))
                    {
                        device_time.tm_day = 1;
                        device_time.tm_mon++;
                    }
                }
                else
                {
                    if(device_time.tm_day > MaxDayArray[device_time.tm_mon-1])
                    {
                        device_time.tm_day = 1;
                        device_time.tm_mon++;
                        if(device_time.tm_mon > 12)
                        {
                            device_time.tm_mon = 1;
                            device_time.tm_year++;
                            if(device_time.tm_year > 2099)
                            {
                                device_time.tm_year = 2000;
                            }
                        }
                    }
                }
                //自动计算星期.
                temp = device_time.tm_year - 2000 + 6; //每年365天，52个星期余1天，即每年星期数加1；
                for(i=2000; i<device_time.tm_year; i++) //瑞年，天数多1，即星期数再加1
                {
                    if( ((i%400)==0)||(((i%4)==0)&&((i%100)!=0)) )
                        temp++;
                }
                //本年已经过去的月，根据每月的天数，
                for(i=0; i<device_time.tm_mon-1; i++)
                    temp += MaxDayArray[i];
                //如果本年是瑞年,而且已经过了2月份.
                if(
                    ( ((device_time.tm_year%400)==0) || (((device_time.tm_year%4)==0)&&((device_time.tm_year%100)!=0)) )
                    && (device_time.tm_mon > 2) )
                    temp++;
                //本月已过的天数
                temp += (device_time.tm_day-1);
                //总和除以7，余数就是当天的星期。（0 =星期日）
                temp = temp%7;
                device_time.tm_week = (uchar)temp;
            }
        }
    }
}

//时间的设置：将device_time中的时间设置到
void Time_Set(void)
{
    u32 TimeVar;
    u16 i, temp;

    //计算年的秒数
    TimeVar = 0;
    for(i=2000; i<device_time.tm_year; i++)
    {
        if( ((i%400)==0) || (((i%4)==0)&&((i%100)!=0)) )
        {   //闰年=366天=366*24*60*60
            TimeVar += 366*24*60*60;	//366*86400
        }
        else
        {
            TimeVar += 365*24*60*60;	//365*86400
        }
    }
    //计算月的秒数
    for(i=0; i<device_time.tm_mon-1; i++)
    {
        TimeVar += MaxDayArray[i]*24*60*60;
    }
    if(
        ( ((device_time.tm_year%400)==0) || (((device_time.tm_year%4)==0)&&((device_time.tm_year%100)!=0)) )
        && (device_time.tm_mon > 2) )
    {
        TimeVar += 24*60*60;
    }
    //计算日的秒数
    TimeVar += (device_time.tm_day-1)*24*60*60;
    //计算当天的秒数
    TimeVar += device_time.tm_hour*60*60 + device_time.tm_min*60 + device_time.tm_sec;
    //写入RTC
    RTC_ITConfig(RTC_IT_SEC, DISABLE);
    RTC_WaitForLastTask();
    RTC_SetCounter(TimeVar);
    RTC_WaitForLastTask();
    RTC_ITConfig(RTC_IT_SEC, ENABLE);
    RTC_WaitForLastTask();
    //自动计算星期.
    temp = device_time.tm_year - 2000 + 6; //每年365天，52个星期余1天，即每年星期数加1；
    for(i=2000; i<device_time.tm_year; i++) //瑞年，天数多1，即星期数再加1
    {
        if( ((i%400)==0)||(((i%4)==0)&&((i%100)!=0)) )
            temp++;
    }
    //本年已经过去的月，根据每月的天数，
    for(i=0; i<device_time.tm_mon-1; i++)
        temp += MaxDayArray[i];
    //如果本年是瑞年,而且已经过了2月份.
    if(
        ( ((device_time.tm_year%400)==0) || (((device_time.tm_year%4)==0)&&((device_time.tm_year%100)!=0)) )
        && (device_time.tm_mon > 2) )
    {
        temp++;
    }
    //本月已过的天数
    temp += (device_time.tm_day-1);
    //总和除以7，余数就是当天的星期。（0 =星期日）
    temp = temp%7;
    device_time.tm_week = (uchar)temp;
}

uchar RTC_Configuration(void)
{
    u32 timeout = 0;

    BKP_DeInit();

#if DEBUG > 0
    printf("RTC config.\r\n");
#endif
    //内部晶振LSE
    RCC_LSICmd(ENABLE);
    do {
        //外部不启振，防止死机，
        timeout++;
    } while((RCC_GetFlagStatus(RCC_FLAG_LSIRDY) == RESET)&&(timeout < 0x3FFFFF));
    if(timeout >= 0x3FFFFF)
    {   //出错，不启用RTC
#if DEBUG > 0
        printf("RTC is err.\r\n");
#endif
        return 0;
    }

#if DEBUG > 0
    printf("RTC is LSI.\r\n");
#endif
    RCC_RTCCLKConfig(RCC_RTCCLKSource_LSI);
    RCC_RTCCLKCmd(ENABLE);

    RTC_WaitForSynchro();		//等待启动完成（总线同步）
    RTC_WaitForLastTask();	//等待前面的RTC操作完成

    device_time.tm_year = 2000;
    device_time.tm_mon = 1;
    device_time.tm_day = 1;
    device_time.tm_hour = 0;
    device_time.tm_min = 0;
    device_time.tm_sec = 0;
    device_time.tm_week = 6;

    RTC_ITConfig(RTC_IT_SEC, ENABLE);
    RTC_WaitForLastTask();
//  RTC_SetPrescaler(32767);		//RTC period = RTCCLK/RTC_PR = (32.768 KHz)/(32767+1)
    RTC_SetPrescaler(40000);
    RTC_WaitForLastTask();
    return 1;
}

void RTC_Init(void)
{
    NVIC_InitTypeDef NVIC_InitStructure;
    u8 ret_rtc = 0;
    u16 temp = 0;

    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
    //RTC中断的使能
    NVIC_InitStructure.NVIC_IRQChannel = RTC_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;		//抢占优先级=1
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);	//开PWR、BKR的时钟
    PWR_BackupAccessCmd(ENABLE);			//设置可访问RTC、BKP

    temp = BKP_ReadBackupRegister(BKP_DR1);
#if DEBUG > 0
    printf("BKP_DR1 = 0x%04X.\r\n", temp);
#endif
    if(temp != 0xA5A5)
    {
        ret_rtc = RTC_Configuration();
        if(ret_rtc == 1)
            BKP_WriteBackupRegister(BKP_DR1, 0xA5A5);
    }
    else
    {
        //if(RCC_GetFlagStatus(RCC_FLAG_PORRST) != RESET)
        //{//电源复位
        //}
        //else if(RCC_GetFlagStatus(RCC_FLAG_PINRST) != RESET)
        //{//口线复位
        //}
        RTC_WaitForSynchro();								//等待启动完成（总线同步）
        Time_Regulate();
        RTC_ITConfig(RTC_IT_SEC, ENABLE);
        RTC_WaitForLastTask();
    }

    RCC_ClearFlag();		//清复位标志
}

//实时钟的中断
void RTC_IRQHandler(void)
{
    if(RTC_GetITStatus(RTC_IT_SEC) != RESET)
    {
        RTC_ClearITPendingBit(RTC_IT_SEC);
        Time_Increase();
    }
}

#if DEBUG > 0
#include <Retarget.c>
//调试输出，使用USART3
#ifndef USART1_USE
#define	USART1_USE 1
#else
#error "USART1 already defined!"
#endif
void Debug_Usart_Init(void)
{
    USART_InitTypeDef USART_InitStructure;

    USART_InitStructure.USART_BaudRate = 38400;
    USART_InitStructure.USART_WordLength = USART_WordLength_8b;
    USART_InitStructure.USART_StopBits = USART_StopBits_1;
    USART_InitStructure.USART_Parity = USART_Parity_No;
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
    USART_Init(USART1, &USART_InitStructure);

    USART_Cmd(USART1, ENABLE);

    printf("\n\r\n\r***********************USART Printf***********************\r\n");
    printf("name: QR-TCPIP \r\n");
    printf("Version: ");
    printf(Soft_version);
    printf("\r\n");
    printf("***************************************************************\r\n");
}

#endif		//DEBUG	

int  getkey(void)
{
    return 0;
}

int sendchar(int ch)
{
	#if DEBUG > 0
		USART_SendData(USART1, (u8) ch);
		while(USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET)
		{
		}
	#endif
    return ch;
}

//设备的配置信息
void Get_Device_Info(void)
{
	STMFLASH_Read(FLASH_SAVE_ADDR,(u16*)(&Regdata.Config),sizeof(_Config_obj));
}
//设备的配置信息
void Set_Device_Info(void)
{
	STMFLASH_Write(FLASH_SAVE_ADDR,(u16*)(&Regdata.Config),sizeof(_Config_obj));
}
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
   // SCB->VTOR = 0x8000000 | 0x5000;//设置偏移量
    SystemInit();
    NVIC_Configuration();
    GPIO_Configuration();
    //////////////////////  看门狗 --- 6s左右  //////////////
    IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable);
    IWDG_SetPrescaler(IWDG_Prescaler_64);		//40kHZ/32=0.8ms，40kHZ/64=1.6ms，40kHZ/128=3.2ms，40kHZ/256=6.4ms，
    IWDG_SetReload(0x0fff);		//0.8×4096=3.2s，6.4s，12.8s，25.6s
    IWDG_ReloadCounter();		//喂狗
    IWDG_Enable();
    ////////////////////////////////////////////////////////////
    TB_Init();		//开1ms系统嘀嗒
#if DEBUG > 0
    Debug_Usart_Init();		//USART调试
#endif
    //InitRtc();
    //RTC_Init();
    //SFLASHInit();					//flash存储初始化
    //SFLASH_CS_ReadID();
    delay_ms(10);
    Get_Device_Info();		//设备信息
    Modbus_UART_Init(4800);
    //Ec20_Uart2_Init();
#if DEBUG > 0
    printf("MODBUS 通讯开始\r\n");
#endif
	//Get_Meter_Info();
    IWDG_ReloadCounter();		//喂狗

    while (1)
    {
        if(counter_1ms==0)
        {
            counter_1ms=1;
			if (Regdata.Calendar.mmsec<1000)
				Regdata.Calendar.mmsec++;
			#if DEBUG == -1
				UART_TCP_RxEvent();//下行接收处理
				UART_TCP_TxEvent();//下行发送处理
			#endif
        }
        if(Timebase_delay_5ms == 0)
        {
            CPU_Usage_begin = Timebase_ms;
            Timebase_delay_5ms = 5;
            counter_10ms++;
            counter_100ms++;
            counter_250ms++;
			counter_500ms++;
            counter_1s++;
            counter_3s++;
            //10ms任务
            if(counter_10ms >= (10/counter_base))
            {
                counter_10ms = 0;
                Analyse_Modbusdata();
            }
            //100ms任务
            if(counter_100ms >= (100/counter_base))
            {
                counter_100ms = 0;
                IWDG_ReloadCounter();		//喂狗			
            }
            //250ms任务
            if(counter_250ms>=(250/counter_base))
            {
                counter_250ms=0;				
            }
			
			if(counter_500ms>=(500/counter_base))
			{
				counter_500ms=0;
				Poll_Modbus_Task();
			}

            //1s
            if(counter_1s>=(1000/counter_base))
            {
                counter_1s=0;
                Regdata.Calendar.mmsec = 0;
            }

            if(counter_3s>=(5000/counter_base))
            {
                counter_3s= 0;
                testflag =1;
            }

            CPU_Usage_end = Timebase_ms;
            //计算使用率(1s内的)
            if(CPU_Usage_end > CPU_Usage_begin)
            {
                CPU_Usage_value += CPU_Usage_end - CPU_Usage_begin;
            }
            else if(CPU_Usage_end == CPU_Usage_begin)
            {
                CPU_Usage_value += 0;
            }
            else
            {
                CPU_Usage_value += CPU_Usage_end + 0xffff - CPU_Usage_begin;
            }
            if(counter_1s == 0)
            {
#if DEBUG > 10
                printf("CPU_Usage = %d.\r\n", CPU_Usage_value);
#endif
                CPU_Usage_value = 0;
            }
        }
//		//休眠（任意中断都会唤醒）
//		//__WFI();
    }
}

/******************* (C) COPYRIGHT 2009 STMicroelectronics *****END OF FILE****/
